package com.guo.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author gonghuaiguo
 */
@Configuration
@Slf4j
public class RabbitConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 在对象创建成功后立即执行
     */
    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        // 消费信息发送到交换机成功或失败调用此方法
        log.info("confirm() 回调函数打印 correlationData：" +correlationData);
        log.info("confirm() 回调函数打印 ack：" +ack);
        log.info("confirm() 回调函数打印 cause：" +cause);
    }

    @Override
    public void returnedMessage(ReturnedMessage message) {
        // 发送到队列上失败 才会回调
        log.info("returnedMessage() 回调函数 消息主体："+ message.getMessage().getBody());
        log.info("returnedMessage() 回调函数 应答码："+ message.getReplyCode());
        log.info("returnedMessage() 回调函数 描述："+ message.getReplyText());
        log.info("returnedMessage() 回调函数 消息使用的exchange："+ message.getExchange());
        log.info("returnedMessage() 回调函数 消息使用的路由键："+ message.getRoutingKey());
    }
}
